<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
  <link rel="stylesheet" href="/public/asset/bootstrap.min.css">
  <link rel="stylesheet" href="/public/asset/bootstrap-icons-141.css">
  <link rel="stylesheet" href="/public/asset/style.css">
  
  <script src="/public/asset/jquery.min.js"></script>
  <script src="/public/asset/dayjs.min.js"></script>
  <script src="/public/asset/bootstrap.bundle.min.js"></script>
  <script src="/public/asset/util.js"></script>
  
  <title>Infomation of My Island - iPelago</title>
</head>
<body>
  <div id="root" class="container" style="max-width: 775px; min-width: 400px;"></div>

<script>

const Loading = CreateLoading();
const Alerts = CreateAlerts();

const TitleArea = {
  view: () => m('div').addClass('d-flex justify-content-between align-items-center my-5').append([
    m('div').attr({id:'title'}).addClass('display-6').text('建岛'),
    m('a').attr({href:'/public/home.html',title:'home'}).addClass('btn btn-outline-dark').append(
      m('i').addClass('bi bi-house-door')
    ),
  ]),
};

const NameInput = cc('input');
const AvatarInput = cc('input');
const EmailInput = cc('input');
const LinkInput = cc('input');

const Form = cc('div', null, [
  m('div').addClass('mb-3').append([
    m('label').addClass('form-label fw-bold').attr({for:NameInput.id}).text('Name'),
    m(NameInput).addClass('form-control').attr({type:'text'}),
    m('div').addClass('form-text').text('岛名，相当于用户名或昵称 (必填)'),
  ]),
  m('div').addClass('mb-3').append([
    m('label').addClass('form-label fw-bold').attr({for:EmailInput.id}).text('Email'),
    m(EmailInput).addClass('form-control').attr({type:'text'}),
    m('div').addClass('form-text').text('岛主的真实 email, 可作为后备联系方式。(可留空，但建议填写)'),
  ]),
  m('div').addClass('mb-3').append([
    m('label').addClass('form-label fw-bold').attr({for:AvatarInput.id}).text('Avatar'),
    m(AvatarInput).addClass('form-control').attr({type:'text'}),
    m('div').addClass('form-text').text('头像图片的网址，头像图片应为正方形，建议头像体积控制在 100KB 以下。请确保头像图片能跨域访问。(可留空)'),
  ]),
  m('div').addClass('mb-3').append([
    m('label').addClass('form-label fw-bold').attr({for:LinkInput.id}).text('Link'),
    m(LinkInput).addClass('form-control').attr({type:'text'}),
    m('div').addClass('form-text').text('一个网址，可以是你的个人网站或博客，也可填写其他社交帐号的网址。(可留空)'),
  ]),
]);

const CreateBtn = cc('button');
const UpdateBtn = cc('button');
const MsgBtn = cc('a');
const PublishBtn = cc('button');

const SubmitBtnArea = cc('p', null, [
  m(CreateBtn).text('Create').addClass('btn btn-primary').attr({type:'button'})
    .hide().click(async () => {
      try {
        const body = await newIslandForm();
        ajax({method:'POST',url:'/api/create-my-island',alerts:Alerts,buttonID:CreateBtn.id,body:body},
          () => {
            Alerts.insert('success', '建岛成功');
            $(CreateBtn.id).toggle();
            $(UpdateBtn.id).toggle();
            $(MsgBtn.id).toggle();
            $(PublishBtn.id).toggle();
          });        
      } catch (errMsg) {
        Alerts.insert('danger', errMsg);
      }
  }),
  m(UpdateBtn).text('Update').addClass('btn btn-primary').attr({type:'button'})
    .hide().click(async () => {
      try {
        const body = await newIslandForm();
        ajax({method:'POST',url:'/api/update-my-island',alerts:Alerts,buttonID:UpdateBtn.id,body:body},
          () => {
            Alerts.insert('success', '更新成功');
          });
      } catch (errMsg) {
        Alerts.insert('danger', errMsg);
      }
    }),
  m(MsgBtn).text('Messages').addClass('btn btn-secondary ms-2')
    .attr({type:'button',href:'/public/my-messages.html'}).hide(),
  m(PublishBtn).text('Publish').addClass('btn btn-secondary ms-2').hide().click(() => {
    ajax({method:'GET',url:'/api/publish-newsletter',alerts:Alerts,buttonID:PublishBtn.id},
        () => {
          window.location = '/public/publish.html';
        });
  }),
]);

$('#root').append([
  m(TitleArea),
  m(Loading),
  m(Form).addClass('mt-5').hide(),
  m(Alerts).addClass('my-3'),
  m(SubmitBtnArea).addClass('text-center my-5'),
]);

init();

function init() {
  ajax({method:'GET',url:'/api/get-my-island',alerts:Alerts},
      (island) => {
        $(Form.id).show();
        if (island.ID) {
          $('#title').text('我的小岛');
          $(UpdateBtn.id).show();
          $(MsgBtn.id).show();
          $(PublishBtn.id).show();
          $(NameInput.id).val(island.Name);
          $(EmailInput.id).val(island.Email);
          $(AvatarInput.id).val(island.Avatar);
          $(LinkInput.id).val(island.Link);
        } else {
          $(CreateBtn.id).show();
        }
      }, null, () => {
        $(Loading.id).hide();
      });
}

async function newIslandForm() {
  let avatarAddr;
  try {
    avatarAddr = $(AvatarInput.id).val();
    await checkAvatarSize(avatarAddr);    
  } catch (errMsg) {
    if (errMsg.indexOf('error occurred during the transaction') >= 0) {
      errMsg = '无法访问头像图片(请确保可跨域访问): ' + errMsg;
    }
    throw errMsg;
  }
  const body = new FormData();
  body.set('name', $(NameInput.id).val());
  body.set('email', $(EmailInput.id).val());
  body.set('avatar', avatarAddr);
  body.set('link', $(LinkInput.id).val());
  return body;
}

async function checkAvatarSize(avatarAddr) {
  try {
    const avatar = await ajaxPromise({method:'GET',url:avatarAddr,responseType:'blob'}, 10);
    if (avatar && avatar.size > 500 * 1024) {
      throw '更新失败: 头像图片体积太大';
    }
  } catch (errMsg) {
    throw errMsg;
  }
}

</script>
</body>
</html>